package com.amethyst.swagger3.demo.aop;

import com.amethyst.swagger3.demo.common.exception.BizException;
import com.amethyst.swagger3.demo.enums.CodeEnum;
import com.amethyst.swagger3.demo.model.AuthorUser;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Amethyst
 * @date 2021/10/14
 */
@Aspect
@Component
@Slf4j
public class TokenAspect {

    /**
     * 定义切点Pointcut
     */
    @Pointcut("execution(* com..*.controller.*Controller.*(..))")
    public void methodArgs() {
    }

    @Around("methodArgs()")
    public Object doBefore(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String query = request.getQueryString();
        String token = request.getParameter("token");
        String flag = request.getParameter("flag");


        // 验证请求token为空
        if (null == token || "".equals(token)) {
            throw new BizException(CodeEnum.TOKEN_IS_NULL);
        }

        // 验证调用权限系统失败
        if (!"true".equals(flag)) {
            throw new BizException(CodeEnum.TOKEN_NOT_CHECK);
        }

        // 验证无效token
        if (!"token".equals(token)) {
            throw new BizException(CodeEnum.TOKEN_IS_NOT_VALID);
        }

        AuthorUser auth = new AuthorUser().setName("token").setRole("admin");

        Object[] obj = joinPoint.getArgs();
        for (Object o : obj) {
            if (o instanceof AuthorUser) {
                AuthorUser queryUser = (AuthorUser) o;
                BeanUtils.copyProperties(auth, queryUser);
            }
        }
        return joinPoint.proceed(obj);
    }
}
